

//
//  DidiMainViewController.m
//  didihaha
//
//  Created by 赵忠鹏 on 2017/8/3.
//  Copyright © 2017年 zhaozhongpeng. All rights reserved.
//

#import "DidiMainViewController.h"
#import "MyJourneyMainViewController.h"
#import "DidMainNavView.h"
#import "DidiMainLeftView.h"
#import "startAndStopView.h"
#import "selectedCarTypeView.h"
#import <TencentLBS/TencentLBS.h>

@interface DidiMainViewController ()<TencentLBSLocationManagerDelegate,QMapViewDelegate>

@property (nonatomic, strong)TencentLBSLocationManager *locationManager;
@property (nonatomic, strong)DidMainNavView *topNavView; // 导航 View
@property (nonatomic, strong)DidiMainLeftView *leftMoreView;
@property (nonatomic, strong)startAndStopView *bottomView;
@property (nonatomic, strong)UIView *tempBGView;

@property (nonatomic, strong)selectedCarTypeView *selectedView;
// 定位按钮
@property (nonatomic, strong) UIButton *locationBtn;


@property (nonatomic, weak)QPointAnnotation *yinke;
@property (nonatomic, weak)QPointAnnotation *yinke2;

// 腾讯地图
@property (nonatomic, strong)UIImageView *DiMapImageView;


@end

@implementation DidiMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.mapView setZoomLevel:17.01];
    self.mapView.delegate = self;
    [self configLocationManager];
    [self startSerialLocation];
    [self defalutLocation];
    [self crateUI];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

-(void)crateUI{
    [self.view addSubview:self.topNavView];
    [self.view addSubview:self.locationBtn];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.selectedView];
    [self.view addSubview:self.DiMapImageView];
    [self.view addSubview:self.tempBGView];
    [self.view addSubview:self.leftMoreView];
    
    
    [self.topNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(100);
    }];
    
    
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-10);
        make.height.mas_equalTo(88);
    }];
    
    [self.selectedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomView.mas_left);
        make.bottom.equalTo(self.bottomView.mas_top).offset(-10);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.bottom.equalTo(self.selectedView.mas_top).offset(-20);
        make.width.height.mas_equalTo(25);
    }];
    
    
    [self.tempBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    [self.leftMoreView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.view);
        make.left.equalTo(self.view.mas_left).offset(-self.view.bounds.size.width/2 );
        make.width.mas_equalTo(self.view.bounds.size.width/2);
    }];
    
    [self.DiMapImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bottomView.mas_right);
        make.bottom.equalTo(self.bottomView.mas_top).offset(-10);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(20);
    }];
}

// 设置默认位置
- (void)defalutLocation{
    
    QPointAnnotation *defalut = [[QPointAnnotation alloc] init];
    defalut.coordinate = CLLocationCoordinate2DMake(39.890452,116.357548);
    [self.mapView addAnnotation:defalut];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.890452,116.357548)animated:YES];
        
    });
}




- (void)configLocationManager
{
    self.locationManager = [[TencentLBSLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setApiKey:@"BT3BZ-OONR4-OY4UD-DTXSI-QGB73-6DBPT"];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    // 需要后台定位的话，可以设置此属性为YES。
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    // 如果需要POI信息的话，根据所需要的级别来设定，定位结果将会根据设定的POI级别来返回，如：
    [self.locationManager setRequestLevel:TencentLBSRequestLevelName];
    
    // 申请的定位权限，得和在info.list申请的权限对应才有效
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

// 单次定位
- (void)startSingleLocation {
    [self.locationManager requestLocationWithCompletionBlock:
     ^(TencentLBSLocation *location, NSError *error) {
         NSLog(@"%@, %@, %@", location.location, location.name, location.address);
     }];
}

// 连续定位
- (void)startSerialLocation {
    //开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)stopSerialLocation {
    //停止定位
    [self.locationManager stopUpdatingLocation];
}

- (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                 didFailWithError:(NSError *)error {
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    if (authorizationStatus == kCLAuthorizationStatusDenied ||
        authorizationStatus == kCLAuthorizationStatusRestricted) {
        //        [self.displayLabel setText:@"定位权限没开启！"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"定位权限未开启，是否开启？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"是"
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction * _Nonnull action) {
                                                    if( [[UIApplication sharedApplication]canOpenURL:
                                                         [NSURL URLWithString:UIApplicationOpenSettingsURLString]] ) {
                                                        [[UIApplication sharedApplication] openURL:
                                                         [NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                                                    }
                                                }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"否"
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction * _Nonnull action) {
                                                }]];
        
        [self presentViewController:alert animated:true completion:nil];
        
    } else {
//        [self.displayLabel setText:[NSString stringWithFormat:@"%@", error]];
    }
}


- (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager
                didUpdateLocation:(TencentLBSLocation *)location {
    //定位结果
    NSLog(@"location:%@", location.location);
    
    
    //获取停止定位的状态
    dispatch_async(dispatch_get_main_queue(), ^{
        
//        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(location.location.coordinate.latitude,location.location.coordinate.longitude)animated:YES];
        
        if (self.yinke) {
            [self.mapView removeAnnotation:self.yinke];
        }
        
        if (self.yinke2) {
            [self.mapView removeAnnotation:self.yinke2];
        }
        
        QPointAnnotation *yinke = [[QPointAnnotation alloc] init];
        yinke.coordinate = CLLocationCoordinate2DMake(location.location.coordinate.latitude,location.location.coordinate.longitude);
        self.yinke = yinke;
        
        QPointAnnotation *yinke2 = [[QPointAnnotation alloc] init];
        yinke2.coordinate = CLLocationCoordinate2DMake(location.location.coordinate.latitude,location.location.coordinate.longitude);
        self.yinke2 = yinke2;
        
        //向mapview添加annotation
        [self.mapView addAnnotation:yinke];
        [self.mapView addAnnotation:yinke2];
        
            

        
    });
    
}

-(QAnnotationView *)mapView:(QMapView *)mapView
          viewForAnnotation:(id<QAnnotation>)annotation {
    static NSString *customReuseIndentifier = @"custReuseIdentifieer";
    
    if ([annotation isKindOfClass:[QPointAnnotation class]]) {
        if ([annotation isEqual:[mapView.annotations objectAtIndex:0]]) {// 初始位置
            //添加自定义annotation
            CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndentifier];
            if (annotationView == nil) {
                annotationView = [[CustomAnnotationView alloc]
                                  initWithAnnotation:annotation
                                  reuseIdentifier:customReuseIndentifier];
                annotationView.draggable = YES;
                //自定义的annotation图标
                UIImage *image = [UIImage imageNamed:@"common_icon_map_start_point"];
                annotationView.image = image;
                annotationView.centerOffset = CGPointMake(image.size.width / 2, - image.size.height / 2);
                annotationView.selected = YES;
                return annotationView;
            }
            
        }else if ([annotation isEqual:[mapView.annotations objectAtIndex:1]]){ //
            //添加自定义annotation
            CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndentifier];
            if (annotationView == nil) {
                annotationView = [[CustomAnnotationView alloc]
                                  initWithAnnotation:annotation
                                  reuseIdentifier:customReuseIndentifier];
                annotationView.userInteractionEnabled = NO;
                //自定义的annotation图标
                UIImage *image = [UIImage imageNamed:@"map_point_location_regular_bg"];
                annotationView.image = image;
                return annotationView;
            }
        }else if ([annotation isEqual:[mapView.annotations objectAtIndex:2]]){
            //添加自定义annotation
            CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndentifier];
            if (annotationView == nil) {
                annotationView = [[CustomAnnotationView alloc]
                                  initWithAnnotation:annotation
                                  reuseIdentifier:customReuseIndentifier];
                annotationView.userInteractionEnabled = NO;
                //自定义的annotation图标
                UIImage *image = [UIImage imageNamed:@"map_point_location_regular_pic"];
                annotationView.image = image;
                return annotationView;
            }
        }
    }
    return nil;
    
}

#pragma mark - 懒加载

- (selectedCarTypeView *)selectedView{
    if (_selectedView == nil) {
        _selectedView = [[selectedCarTypeView alloc] init];
    }
    return _selectedView;
}

- (DidMainNavView *)topNavView{
    if (_topNavView == nil) {
        _topNavView = [[DidMainNavView alloc] init];
        [_topNavView.personMessageBtn addTarget:self action:@selector(personLeftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _topNavView;
}

- (UIView *)tempBGView{
    if (_tempBGView == nil) {
        _tempBGView = [[UIView alloc] init];
        _tempBGView.backgroundColor = [UIColor lightGrayColor];
        _tempBGView.alpha = 0.3;
        _tempBGView.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
        [_tempBGView addGestureRecognizer:tap];
    }
    return _tempBGView;
}

- (DidiMainLeftView *)leftMoreView{
    if (_leftMoreView == nil) {
        _leftMoreView = [[DidiMainLeftView alloc] init];
        [_leftMoreView.journeyBtn addTarget:self action:@selector(tripButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftMoreView;
}

- (UIButton *)locationBtn{
    if (_locationBtn == nil) {
        _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_locationBtn setImage:[UIImage imageNamed:@"common_icon_map_Reset"] forState:UIControlStateNormal];
    }
    return _locationBtn;
}

- (startAndStopView *)bottomView{
    if (_bottomView == nil) {
        _bottomView = [[startAndStopView alloc] init];
    }
    return _bottomView;
}

- (UIImageView *)DiMapImageView{
    if (_DiMapImageView == nil) {
        _DiMapImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tengxunDiTu"]];
    }
    return _DiMapImageView;
}


#pragma mark - 按钮触发方法
- (void)personLeftBtnClick:(UIButton *)btn{
    
    // 隐藏状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
    // 加背景
    self.tempBGView.hidden = NO;
    // 更新坐标
    [self.view layoutIfNeeded];
    
    [UIView animateWithDuration:0.4 animations:^{
        [self.leftMoreView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
        }];
        [self.view layoutIfNeeded];
    }];
}

- (void)tapClick{
    // 隐藏状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
    // 加背景
    self.tempBGView.hidden = YES;
    // 更新坐标
    [self.view layoutIfNeeded];
    
    [UIView animateWithDuration:0.4 animations:^{
        [self.leftMoreView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(-self.view.bounds.size.width/2 );
        }];
        [self.view layoutIfNeeded];
    }];
}
#pragma mark - 按钮触发方法
-(void)tripButtonClick:(UIButton *)btn{
    MyJourneyMainViewController *vc = [[MyJourneyMainViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}



@end
